package cn.ug.activity.web.controller;

import cn.ug.activity.bean.GiftBean;
import cn.ug.activity.bean.GiftRecordBean;
import cn.ug.activity.bean.GiftStatisticsBean;
import cn.ug.activity.bean.MemberExchangesBean;
import cn.ug.activity.mapper.entity.ActivityCard;
import cn.ug.activity.mapper.entity.ActivityGift;
import cn.ug.activity.mapper.entity.ActivityGiftRecord;
import cn.ug.activity.service.ActivityGiftService;
import cn.ug.bean.LoginBean;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Order;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.login.LoginHelper;
import cn.ug.enums.RateKeyEnum;
import cn.ug.feign.MemberUserService;
import cn.ug.feign.RateSettingsService;
import cn.ug.member.bean.response.MemberUserBean;
import cn.ug.member.mq.MemberPasswordStatusMQ;
import cn.ug.mq.DelayMessagePostProcessor;
import cn.ug.util.ExportExcelUtil;
import cn.ug.util.PaginationUtil;
import cn.ug.util.UF;
import cn.ug.web.controller.BaseController;
import cn.ug.web.controller.ExportExcelController;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static cn.ug.config.QueueName.QUEUE_MEMBER_PASSWORD_STATUS_DELAY;
import static cn.ug.util.ConstantUtil.COMMA;

@RestController
@RequestMapping("gift")
public class ActivityGiftController extends BaseController {
    @Autowired
    private ActivityGiftService activityGiftService;
    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private RateSettingsService rateSettingsService;
    @Autowired
    private AmqpTemplate amqpTemplate;

    @GetMapping("/limit")
    public SerializeObject limit(@RequestHeader String accessToken, int giftId) {
        if (giftId < 1) {
            return new SerializeObjectError("00000002");
        }
        LoginBean loginBean = LoginHelper.getLoginBean();
        if (loginBean == null || StringUtils.isBlank(loginBean.getAccessToken()) || !StringUtils.equals(accessToken, loginBean.getAccessToken())) {
            return new SerializeObject<>(ResultType.UNLOGIN, "00000102");
        }
        String memberId = LoginHelper.getLoginId();
        return activityGiftService.limit(memberId, giftId);
    }

    @PostMapping("/record")
    public SerializeObject exchange(@RequestHeader String accessToken, int giftId, String payPassword) {
        if (giftId < 1 || StringUtils.isBlank(payPassword)) {
            return new SerializeObjectError("00000002");
        }
        payPassword = UF.toString(payPassword);
        LoginBean loginBean = LoginHelper.getLoginBean();
        if (loginBean == null || StringUtils.isBlank(loginBean.getAccessToken()) || !StringUtils.equals(accessToken, loginBean.getAccessToken())) {
            return new SerializeObject<>(ResultType.UNLOGIN, "00000102");
        }
        String memberId = LoginHelper.getLoginId();
        if(StringUtils.isBlank(memberId)) {
            return new SerializeObjectError("00000102");
        }
        SerializeObject obj = memberUserService.validatePayPassword(memberId, payPassword);
        if (null == obj || obj.getCode() != ResultType.NORMAL) {
            SerializeObject paramBean  = rateSettingsService.get(RateKeyEnum.TRADE_PASSWORD.getKey());
            if (paramBean != null && paramBean.getData() != null) {
                JSONObject json = JSON.parseObject(JSONObject.toJSONString(paramBean.getData()));
                int isLimited = json.getIntValue("isLimited");
                int wrongTimes = json.getIntValue("wrongTimes");
                int minutes = json.getIntValue("minutes");
                if (isLimited == 1) {
                    SerializeObject<MemberUserBean> memberBean = memberUserService.findById(memberId);
                    if (null == memberBean || memberBean.getData() == null) {
                        return new SerializeObjectError("00000102");
                    }
                    MemberUserBean memberUserBean = memberBean.getData();
                    if (isLimited == 1 && memberUserBean.getTrdpassdStatus() == 1) {
                        SerializeObjectError result = new SerializeObjectError<>("22000141");
                        String msg = String.format(result.getMsg(), wrongTimes, minutes);
                        result.setMsg(msg);
                        return result;
                    }
                    int actualWrongTimes = memberUserBean.getTrdpassdWrongTimes();
                    actualWrongTimes++;
                    int status = 0;
                    if (wrongTimes <= actualWrongTimes) {
                        status = 1;
                    }
                    memberUserService.modifyWrongTimes(memberUserBean.getId(), 2, actualWrongTimes, status);
                    if (wrongTimes <= actualWrongTimes) {
                        MemberPasswordStatusMQ mq = new MemberPasswordStatusMQ();
                        mq.setMemberId(memberUserBean.getId());
                        mq.setType(2);
                        amqpTemplate.convertAndSend(QUEUE_MEMBER_PASSWORD_STATUS_DELAY, mq, new DelayMessagePostProcessor(minutes * 60 * 1000));

                        SerializeObjectError result = new SerializeObjectError<>("22000141");
                        String msg = String.format(result.getMsg(), wrongTimes, minutes);
                        result.setMsg(msg);
                        return result;
                    }
                }
            }
            return new SerializeObjectError<>("22000145");
        }
        memberUserService.modifyWrongTimes(memberId, 2, 0, 0);
        String orderNO = activityGiftService.exchange(memberId, giftId);
        if (StringUtils.isNotBlank(orderNO)) {
            return new SerializeObject(ResultType.NORMAL, "00000001", orderNO);
        } else {
            return new SerializeObjectError("00000005");
        }
    }

    @PostMapping
    public SerializeObject save(@RequestHeader String accessToken, ActivityGift entity, HttpServletRequest request) {
        if(null == entity || StringUtils.isBlank(entity.getName())) {
            return new SerializeObjectError("22000130");
        }
        entity.setCreatorId(LoginHelper.getLoginId());
        entity.setCreatorName(LoginHelper.getName());
        if (entity.getType()  <= 0) {
            return new SerializeObjectError("22000131");
        }
        if (entity.getInitNum() <= 0) {
            return new SerializeObjectError("22000132");
        }
        if (entity.getTotalPrice() == null || entity.getTotalPrice().doubleValue() <= 0 || entity.getPrice() < 0) {
            return new SerializeObjectError("22000133");
        }
        if (entity.getType() == 1 && entity.getCouponId() <= 0) {
            return new SerializeObjectError("22000134");
        }
        if (entity.getMarketPrice() == null || entity.getMarketPrice().doubleValue() <= 0) {
            return new SerializeObjectError("22000135");
        }
        if (StringUtils.isBlank(entity.getIntroduction())) {
            return new SerializeObjectError("22000136");
        }
        if (StringUtils.isBlank(entity.getRemark())) {
            return new SerializeObjectError("22000137");
        }
        if (StringUtils.isBlank(entity.getImgUrl())) {
            return new SerializeObjectError("22000138");
        }
        List<ActivityCard> cards = new ArrayList<ActivityCard>();
        if (entity.getType() == 2) {
            CommonsMultipartResolver multipartResolver  = new CommonsMultipartResolver(request.getSession().getServletContext());
            if(multipartResolver.isMultipart(request)){
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                Iterator<String> iterator = multiRequest.getFileNames();
                while(iterator.hasNext()){
                    MultipartFile file = multiRequest.getFile(iterator.next());
                    BufferedReader br= null;
                    try {
                        InputStreamReader isr = new InputStreamReader(file.getInputStream(),"utf-8");
                        br = new BufferedReader(isr);
                        String line = "";
                        int index = 0;
                        while ((line = br.readLine()) != null) {
                            index ++;
                            if(index == 1){
                                continue;
                            }
                            if(StringUtils.isNotBlank(line)){
                                if(line.split(COMMA).length == 1){
                                    ActivityCard card = new ActivityCard();
                                    card.setPassword(line.split(COMMA)[0]);
                                    cards.add(card);
                                } else if (line.split(COMMA).length == 2) {
                                    ActivityCard card = new ActivityCard();
                                    card.setCardNO(line.split(COMMA)[0]);
                                    card.setPassword(line.split(COMMA)[1]);
                                    cards.add(card);
                                }
                            }
                        }
                    } catch (Exception e) {
                        return new SerializeObjectError("22000015");
                    }finally{
                        if(br!=null){
                            try{
                                br.close();
                                br=null;
                            }catch(IOException e){
                                e.printStackTrace();
                                info(e.getMessage());
                            }
                        }
                    }
                }
            }
            if (cards == null || cards.size() == 0) {
                return new SerializeObjectError("22000139");
            }
            entity.setInitNum(cards.size());
        }
        if (activityGiftService.save(entity, cards)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PostMapping("/save/after/online")
    public SerializeObject saveAfterOnline(@RequestHeader String accessToken, ActivityGift entity) {
        if (StringUtils.isBlank(entity.getIntroduction())) {
            return new SerializeObjectError("22000136");
        }
        if (StringUtils.isBlank(entity.getRemark())) {
            return new SerializeObjectError("22000137");
        }
        if (StringUtils.isBlank(entity.getImgUrl())) {
            return new SerializeObjectError("22000138");
        }
        if (activityGiftService.saveAfterOnline(entity)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @GetMapping(value = "/{id}")
    public SerializeObject get(@RequestHeader String accessToken, @PathVariable int id) {
        return new SerializeObject<>(ResultType.NORMAL, activityGiftService.getGift(id));
    }

    @PostMapping("/hot")
    public SerializeObject hot(@RequestHeader String accessToken, int id, int hot) {
        if (hot == 1) {
            int num = activityGiftService.countForHot();
            if (num >= 2) {
                return new SerializeObjectError("22000140");
            }
        }
        if (activityGiftService.hot(id, hot)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PostMapping("/status")
    public SerializeObject updateStatus(@RequestHeader String accessToken, int id, int status, String remark) {
        String auditorId = LoginHelper.getLoginId();
        String auditorNamae = LoginHelper.getName();
        if (activityGiftService.updateStatus(id, status, remark, auditorId, auditorNamae)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @GetMapping(value = "/list")
    public SerializeObject<DataTable<ActivityGift>> list(@RequestHeader String accessToken, Page page, Order order, Integer status, Integer auditStatus, Integer type, String name, String startDate, String endDate) {
        status = status == null ? 0 : status;
        auditStatus = auditStatus == null ? 0 : auditStatus;
        type = type == null ? 0 : type;
        name = UF.toString(name);
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        int total = activityGiftService.count(status, type, name, startDate, endDate, auditStatus);
        page.setTotal(total);
        if (total > 0) {
            List<ActivityGift> list = activityGiftService.query(status, type, name, startDate, endDate, auditStatus, order.getOrder(), order.getSort(), PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<ActivityGift>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<ActivityGift>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<ActivityGift>()));
    }

    @GetMapping(value = "/export")
    public void queryForExport(HttpServletResponse response, Order order, Integer status, Integer auditStatus, Integer type, String name, String startDate, String endDate) {
        status = status == null ? 0 : status;
        auditStatus = auditStatus == null ? 0 : auditStatus;
        type = type == null ? 0 : type;
        name = UF.toString(name);
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        List<ActivityGift> list = activityGiftService.query(status, type, name, startDate, endDate, auditStatus, order.getOrder(), order.getSort(), 0, 0);
        if (list == null) {
            list = new ArrayList<ActivityGift>();
        }
        int index = 1;
        for (ActivityGift bean : list) {
            bean.setIndex(index);
            index++;
            if (bean.getType() == 1) {
                bean.setTypeMark("优惠礼券");
            } else if (bean.getType() == 2) {
                bean.setTypeMark("热门权益");
            } else if (bean.getType() == 3) {
                bean.setTypeMark("精品实物");
            }
            if (bean.getStatus() == 0) {
                bean.setStatusMark("待审核");
            } else if (bean.getStatus() == 2) {
                bean.setStatusMark("已拒绝");
            } else {
                bean.setStatusMark("已通过");
            }
        }
        if (status == 0) {
            String fileName = "未审核礼品列表";
            String[] columnNames = { "序号", "礼品ID","礼品名称", "礼品类型", "礼品数量", "创建时间", "创建者"};
            String[] columns = {"index",  "id", "name", "typeMark", "balance", "addTime", "creatorName"};
            ExportExcelController<ActivityGift> export = new ExportExcelController<ActivityGift>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        } else if (status == 1) {
            String fileName = "在售礼品管理";
            String[] columnNames = { "序号", "礼品ID","礼品名称", "礼品类型", "库存数量", "礼品单价（个）", "已兑数量", "创建人", "创建时间"};
            String[] columns = {"index",  "id", "name", "typeMark", "balance", "price", "exchanges", "creatorName", "addTime"};
            ExportExcelController<ActivityGift> export = new ExportExcelController<ActivityGift>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        } else if (status == 2) {
            String fileName = "已审核礼品列表";
            String[] columnNames = { "序号", "礼品ID","礼品名称", "礼品类型", "礼品数量", "审核时间", "审核状态", "审核人", "创建人"};
            String[] columns = {"index",  "id", "name", "typeMark", "balance", "shelfTime", "statusMark", "auditorName", "creatorName"};
            ExportExcelController<ActivityGift> export = new ExportExcelController<ActivityGift>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        } else {
            String fileName = "历史礼品管理";
            String[] columnNames = { "序号", "礼品ID","礼品名称", "礼品类型", "礼品单价（个）", "已兑数量", "下架时间", "下架原因"};
            String[] columns = {"index",  "id", "name", "typeMark", "price", "exchanges", "unshelfTime", "reason"};
            ExportExcelController<ActivityGift> export = new ExportExcelController<ActivityGift>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }

    @GetMapping(value = "/record/list")
    public SerializeObject<DataTable<ActivityGiftRecord>> list(@RequestHeader String accessToken, Page page, Order order, String memberId, Integer giftId, Integer giftType, String giftName, String startDate, String endDate) {
        giftType = giftType == null ? 0 : giftType;
        giftId = giftId == null ? 0 : giftId;
        memberId = UF.toString(memberId);
        giftName = UF.toString(giftName);
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        int total = activityGiftService.countRecord(memberId, giftId, giftName, giftType, startDate, endDate);
        page.setTotal(total);
        if (total > 0) {
            List<ActivityGiftRecord> list = activityGiftService.queryRecord(memberId, giftId, giftName, giftType, startDate, endDate, order.getOrder(), order.getSort(), PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            if (list != null && list.size() > 0) {
                for (ActivityGiftRecord bean : list) {
                    if (StringUtils.isNotBlank(bean.getMemberMobile())) {
                        bean.setMemberMobile(StringUtils.substring(bean.getMemberMobile(), 0, 3) +"****"+ StringUtils.substring(bean.getMemberMobile(), 7));
                    }
                }
            }
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<ActivityGiftRecord>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<ActivityGiftRecord>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<ActivityGiftRecord>()));
    }

    @GetMapping(value = "/record/export")
    public void queryForExport(HttpServletResponse response, Order order, String memberId, Integer giftId, Integer giftType, String giftName, String startDate, String endDate) {
        giftId = giftId == null ? 0 : giftId;
        giftType = giftType == null ? 0 : giftType;
        memberId = UF.toString(memberId);
        giftName = UF.toString(giftName);
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        List<ActivityGiftRecord> list = activityGiftService.queryRecord(memberId, giftId, giftName, giftType, startDate, endDate, order.getOrder(), order.getSort(), 0, 0);
        if (list == null) {
            list = new ArrayList<ActivityGiftRecord>();
        }
        int index = 1;
        for (ActivityGiftRecord bean : list) {
            bean.setIndex(index);
            index++;
            if (bean.getGiftType() == 1) {
                bean.setGiftTypeMark("优惠礼券");
            } else if (bean.getGiftType() == 2) {
                bean.setGiftTypeMark("热门权益");
            } else if (bean.getGiftType() == 3) {
                bean.setGiftTypeMark("精品实物");
            }
            if (StringUtils.isNotBlank(bean.getMemberMobile())) {
                bean.setMemberMobile(StringUtils.substring(bean.getMemberMobile(), 0, 3) +"****"+ StringUtils.substring(bean.getMemberMobile(), 7));
            }
        }
        if (giftId > 0) {
            String fileName = "兑换礼品统计详表";
            String[] columnNames = { "序号", "订单流水号","兑换时间", "用户账户", "用户姓名"};
            String[] columns = {"index",  "orderNO", "addTime", "memberMobile", "memberName"};
            ExportExcelController<ActivityGiftRecord> export = new ExportExcelController<ActivityGiftRecord>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        } else if (StringUtils.isNotBlank(memberId)) {
            String fileName = "用户兑换礼品记录详表";
            String[] columnNames = { "序号", "礼品id","礼品名称", "礼品类型", "兑换时间", "兑换金额（金豆）"};
            String[] columns = {"index",  "giftId", "giftName", "giftTypeMark", "addTime", "payBeans"};
            ExportExcelController<ActivityGiftRecord> export = new ExportExcelController<ActivityGiftRecord>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        } else {
            String fileName = "兑换礼品订单记录";
            String[] columnNames = { "序号", "订单流水号","礼品名称", "礼品类型", "手机号", "用户姓名", "下单时间", "兑换支付金额（金豆）"};
            String[] columns = {"index",  "orderNO", "giftName", "giftTypeMark", "memberMobile", "memberName", "addTime", "payBeans"};
            ExportExcelController<ActivityGiftRecord> export = new ExportExcelController<ActivityGiftRecord>();
            export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }

    @GetMapping(value = "/member/list")
    public SerializeObject<DataTable<MemberExchangesBean>> list(@RequestHeader String accessToken, Page page, Order order, String memberMobile, String memberName, String startDate, String endDate, Integer startNum, Integer endNum) {
        startNum = startNum == null ? -1 : startNum;
        endNum = endNum == null ? -1 : endNum;
        memberMobile = UF.toString(memberMobile);
        memberName = UF.toString(memberName);
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        int total = activityGiftService.countForExchanges(memberMobile, memberName, startDate, endDate, startNum, endNum);
        page.setTotal(total);
        if (total > 0) {
            List<MemberExchangesBean> list = activityGiftService.queryForExchanges(memberMobile, memberName, startDate, endDate, startNum, endNum, order.getOrder(), order.getSort(), PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberExchangesBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberExchangesBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<MemberExchangesBean>()));
    }

    @GetMapping(value = "/member/export")
    public void queryForExport(HttpServletResponse response, Order order, String memberMobile, String memberName, String startDate, String endDate, Integer startNum, Integer endNum) {
        startNum = startNum == null ? -1 : startNum;
        endNum = endNum == null ? -1 : endNum;
        memberMobile = UF.toString(memberMobile);
        memberName = UF.toString(memberName);
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        List<MemberExchangesBean> list = activityGiftService.queryForExchanges(memberMobile, memberName, startDate, endDate, startNum, endNum, order.getOrder(), order.getSort(), 0, 0);
        if (list == null) {
            list = new ArrayList<MemberExchangesBean>();
        }
        int index = 1;
        for (MemberExchangesBean bean : list) {
            bean.setIndex(index);
            index++;
        }
        String fileName = "用户兑换礼品记录表";
        String[] columnNames = { "序号", "手机号","姓名", "已兑换礼品总数", "账户创建时间"};
        String[] columns = {"index",  "memberMobile", "memberName", "exchanges", "addTime"};
        ExportExcelController<MemberExchangesBean> export = new ExportExcelController<MemberExchangesBean>();
        export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
    }

    @GetMapping(value = "/statistics/list")
    public SerializeObject<DataTable<GiftStatisticsBean>> list(@RequestHeader String accessToken, Page page, Order order, String giftName, Integer startNum, Integer endNum, Integer giftType, Integer status) {
        startNum = startNum == null ? -1 : startNum;
        endNum = endNum == null ? -1 : endNum;
        giftName = UF.toString(giftName);
        giftType = giftType == null ? 0 : giftType;
        status = status == null ? 0 : status;
        int total = activityGiftService.countForExchanges(giftName, startNum, endNum, giftType, status);
        page.setTotal(total);
        if (total > 0) {
            List<GiftStatisticsBean> list = activityGiftService.queryForExchanges(giftName, startNum, endNum, giftType, status, order.getSort(), PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<GiftStatisticsBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<GiftStatisticsBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<GiftStatisticsBean>()));
    }

    @GetMapping(value = "/statistics/export")
    public void queryForExport(HttpServletResponse response, Order order, String giftName, Integer startNum, Integer endNum, Integer giftType, Integer status) {
        startNum = startNum == null ? -1 : startNum;
        endNum = endNum == null ? -1 : endNum;
        giftName = UF.toString(giftName);
        giftType = giftType == null ? 0 : giftType;
        status = status == null ? 0 : status;
        List<GiftStatisticsBean> list = activityGiftService.queryForExchanges(giftName, startNum, endNum, giftType, status, order.getSort(), 0, 0);
        if (list == null) {
            list = new ArrayList<GiftStatisticsBean>();
        }
        int index = 1;
        for (GiftStatisticsBean bean : list) {
            bean.setIndex(index);
            index++;
            if (bean.getGiftType() == 1) {
                bean.setGiftTypeMark("优惠礼券");
            } else if (bean.getGiftType() == 2) {
                bean.setGiftTypeMark("热门权益");
            } else if (bean.getGiftType() == 3) {
                bean.setGiftTypeMark("精品实物");
            }
            if (bean.getStatus() == 1) {
                bean.setStatusMark("在售中");
            } else {
                bean.setStatusMark("已下架");
            }
        }

        String fileName = "兑换礼品统计表";
        String[] columnNames = { "序号", "礼品ID","礼品名称", "礼品类型", "礼品状态", "礼品兑换数量"};
        String[] columns = {"index",  "giftId", "giftName", "giftTypeMark", "statusMark", "exchanges"};
        ExportExcelController<GiftStatisticsBean> export = new ExportExcelController<GiftStatisticsBean>();
        export.exportExcel(fileName, fileName, columnNames, columns, list, response, ExportExcelUtil.EXCEL_FILE_2003);
    }

    @GetMapping(value = "/hot/list")
    public SerializeObject<List<GiftBean>> list(@RequestHeader String accessToken) {
        List<GiftBean> list = activityGiftService.queryForHotList();
        return new SerializeObject<>(ResultType.NORMAL, list);
    }

    @GetMapping(value = "/display/list")
    public SerializeObject<DataTable<GiftBean>> list(@RequestHeader String accessToken, Page page, Integer giftType) {
        giftType = giftType == null ? 0 : giftType;
        int total = activityGiftService.queryForAppCount(giftType);
        page.setTotal(total);
        if (total > 0) {
            List<GiftBean> list = activityGiftService.queryForAppList(giftType, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<GiftBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<GiftBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<GiftBean>()));
    }

    @GetMapping(value = "/detail")
    public SerializeObject<GiftBean> list(@RequestHeader String accessToken, int id) {
        return new SerializeObject<>(ResultType.NORMAL, activityGiftService.findBeanById(id));
    }

    @GetMapping(value = "/member/record")
    public SerializeObject<DataTable<GiftRecordBean>> list(@RequestHeader String accessToken, Page page) {
        LoginBean loginBean = LoginHelper.getLoginBean();
        if (loginBean == null || StringUtils.isBlank(loginBean.getAccessToken()) || !StringUtils.equals(accessToken, loginBean.getAccessToken())) {
            return new SerializeObject<>(ResultType.UNLOGIN, "00000102");
        }
        String memberId = LoginHelper.getLoginId();
        int total = activityGiftService.queryForAppCount(memberId);
        page.setTotal(total);
        if (total > 0) {
            List<GiftRecordBean> list = activityGiftService.queryForAppList(memberId, PaginationUtil.getOffset(page.getPageNum(), page.getPageSize()), PaginationUtil.getPageSize(page.getPageSize()));
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<GiftRecordBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<GiftRecordBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<GiftRecordBean>()));
    }

    @GetMapping(value = "/record/detail")
    public SerializeObject<GiftRecordBean> list(@RequestHeader String accessToken, String orderNO) {
        return new SerializeObject<>(ResultType.NORMAL, activityGiftService.findByOrderNO(orderNO));
    }
}
